<?php

namespace app\system\controller\system;

use app\admin\model\AdminRule;
use app\common\controller\System;
use ba\Random;
use think\facade\Db;

/**
 * 子站管理
 *
 */
class Substation extends System {
    /**
     * Substation模型对象
     * @var \app\admin\model\system\Substation
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array|string $quickSearchField = ['name'];

    public function initialize():void {
        parent::initialize();
        $this->model = new \app\system\model\system\Substation;
    }


    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model->with(['admin'])
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function del(array $ids = []):void {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk = $this->model->getPk();
        $data = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($data as $v) {
                db::name('admin')->where(['outstation_id' => $v->id])->delete();
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }


    public function edit():void {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->with(['admin'])->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $row['rules'] = Db::name('admin_access')->where(['admin_id' => $row['admin']['id']])->value('rules');
        $row['rules'] = empty($row['rules']) ? [] : explode(',', $row['rules']);

        $row['account'] = $row['admin']['username'];
        $row['password'] = $row['admin']['password'];

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
//            print_r($data);die;

            if(empty($data['host'])) $this->error('域名不能为空');
            if(empty($data['account'])) $this->error('账号不能为空');
            $where = [
                ['id', '<>', $id],
                ['host', '=', $data['host']]
            ];
            $res = Db::name('system_substation')->where($where)->find();
            if($res) $this->error('域名已存在');

            $where = [
                ['id', '<>', $row['admin']['id']],
                ['username', '=', $data['account']],
                ['outstation_id', '=', $id]
            ];
            $res = db::name('admin')->where($where)->find();
            if($res) $this->error('账号已存在');

            $data = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {


                $admin_access_update = [
                    'rules' => implode(',', $data['rules'])
                ];
                db::name('admin_access')->where(['admin_id' => $row['admin']['id']])->update($admin_access_update);

                $admin_update = [
                    'username' => $data['account'],
                    'update_time' => $this->timestamp
                ];
                if(!empty($data['password'])){
                    $salt   = Random::build('alnum', 16);
                    $passwd = encrypt_password($data['password'], $salt);
                    $admin_update['password'] = $passwd;
                    $admin_update['salt'] = $salt;
                }
                db::name('admin')->where(['id' => $row['admin']['id']])->update($admin_update);
                $system_substation_update = [
                    'host' => $data['host'],
                    'name' => $data['name'],
                    'update_time' => $this->timestamp
                ];
                $result = db::name('system_substation')->where(['id' => $id])->update($system_substation_update);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        // 读取所有pid，全部从节点数组移除，父级选择状态由子级决定
        $pidArr = AdminRule::field('pid')
            ->distinct(true)
            ->where('id', 'in', $row->rules)
            ->select()->toArray();
        $rules  = $row['rules'];
        foreach ($pidArr as $item) {
            $ruKey = array_search($item['pid'], $rules);
            if ($ruKey !== false) {
                unset($rules[$ruKey]);
            }
        }
        $row['rules'] = array_values($rules);


        $row['password'] = '';
        $this->success('', [
            'row' => $row
        ]);
    }


    public function add():void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data = $this->excludeFields($data);

            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            if(empty($data['account'])) $this->error('账号不能为空');
            if(empty($data['password'])) $this->error('密码不能为空');
            if(empty($data['host'])) $this->error('请输入网站域名');
            if(Db::name('system_substation')->where(['host' => $data['host']])->find()) $this->error('域名已存在');

            $result = false;
            Db::startTrans();
            try {


                $outstation_insert = [
                    'host' => $data['host'],
                    'name' => empty($data['name']) ? $data['account'] : $data['name'],
                    'create_time' => $this->timestamp
                ];
                $outstation_id = Db::name('system_substation')->insertGetId($outstation_insert);

                $salt   = Random::build('alnum', 16);
                $passwd = encrypt_password($data['password'], $salt);

                $admin_insert = [
                    'outstation_id' => $outstation_id,
                    'username' => $data['account'],
                    'password' => $passwd,
                    'salt' => $salt,
                    'create_time' => $this->timestamp
                ];
                $admin_id = Db::name('admin')->insertGetId($admin_insert);


                $admin_access_insert = [
                    'rules' => implode(',', $data['rules']),
                    'admin_id' => $admin_id
                ];
                $result = db::name('admin_access')->insert($admin_access_insert);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}